package com.xinlianshiye.im.dao.impl;

import java.util.*;

import com.xinlianshiye.im.bean.QFriend;
import com.xinlianshiye.im.bean.QUser;
import com.xinlianshiye.im.bean.QUserGroup;
import com.xinlianshiye.im.response.GroupfriendsList;
import com.xinlianshiye.im.dao.BaseRepository;
import com.xinlianshiye.im.dao.custom.UserGroupDaoCustom;
import com.xinlianshiye.im.response.UserInfo;

public class UserGroupDaoImpl extends BaseRepository implements UserGroupDaoCustom {

    @Override
    public List<GroupfriendsList> findgroupfriendsList(Integer userid) {
        QFriend friend = QFriend.friend1;
        QUser user = QUser.user;
        QUserGroup group = QUserGroup.userGroup;

        Map<Integer, GroupfriendsList> map = new HashMap<>();

        queryFactory
                .select(
                        friend.userGroup.id,
                        friend.userGroup.name,
                        friend.friend.id,
                        friend.friend.username
                )
                .from(friend).rightJoin(friend.userGroup)
                .where(friend.userGroup.user.id.eq(userid))
                .fetch().forEach((tuple) -> {
            Integer groupId = tuple.get(friend.userGroup.id);
            String groupName = tuple.get(friend.userGroup.name);
            Integer userId = tuple.get(friend.friend.id);
            String username = tuple.get(friend.friend.username);
            GroupfriendsList group2;
            if (map.containsKey(groupId)) {
                group2 = map.get(groupId);
            } else {
                group2 = new GroupfriendsList();
                group2.setId(groupId);
                group2.setName(groupName);
                group2.setList(new ArrayList<>());
                map.put(groupId, group2);
            }
            UserInfo user2 = new UserInfo();
            user2.setId(userId);
            user2.setUsername(username);
            group2.getList().add(user2);
        });
        return new ArrayList<>(map.values());
    }
}
